package cn.book.org.service.impl;

import cn.book.basic.exception.BusinessException;
import cn.book.basic.service.impl.BaseServiceImpl;
import cn.book.basic.utils.BaiduAuditUtils;
import cn.book.org.domain.Employee;
import cn.book.org.domain.Shop;
import cn.book.org.mapper.EmployeeMapper;
import cn.book.org.mapper.ShopMapper;
import cn.book.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-07-01
 */

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * @Title: settlement
     * @Description: 店铺入驻方法
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/7/1 14:10
     * @Parameters: [shop]
     * @Return void
     */
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        // 1.判断必要参数是否为空，这里我们应该要全部参数都判断是否为空，我就以名称举例
        if (StringUtils.isEmpty(shop.getName())){
            throw new BusinessException("参数不能为空，请重新输入！");
        }
        // 2.两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码不一致，请重新输入！");
        }

        // 百度AI验证词汇是否违规
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());
        if(!boo) {
            throw new BusinessException("发现违规污言秽语!!");
        }

        // 3.查询店铺是否存在,根据店铺名称查询
        Shop loadShopTmp = shopMapper.loadByName(shop.getName());
        if (loadShopTmp != null){
            throw new BusinessException("店铺已注册，请更换店铺信息！");
        }
        // 4.查询管理员已经注册过，并且还绑定了某个店铺，这种情况我们认为你不符合我们业务要求，抛出异常
        Employee empTmp = employeeMapper.loadByUserName(admin.getUsername());
        // 此处你们可以自己更改为根据主键查询店铺的admin_id
        if (empTmp != null && empTmp.getShopId() != null){
            throw new BusinessException("该管理员已绑定店铺，请更换其他管理员！");
        }
        // 5.管理员没注册，那么注册管理员
        if (empTmp == null){
            // 保存admin，一定要保证返回了主键Id
            employeeMapper.save(admin);
            empTmp = admin;
        }

        // 6.如果走到这里，那么管理员绝对已经注册过了
        // 6.1.将管理员的主键设置到店铺的外键
        shop.setAdminId(empTmp.getId());
        // 6.2.保存店铺,一定要返回主键
        shopMapper.save(shop);
        // 6.3.将店铺的主键设置到管理员的外键
        empTmp.setShopId(shop.getId());
        // 6.4.修改员工数据
        employeeMapper.update(empTmp);
    }
}
